package org.NooLab.itexx.retrieval;

import java.io.IOException;

import org.NooLab.itexx.ITexxWindowIntf;
import org.NooLab.itexx.app.gui.definition.ITexxWindowGui;
import org.NooLab.itexx.app.gui.definition.ITexxWindowGuiIntf;
import org.NooLab.itexx.browser.BrowserWorker;
import org.NooLab.itexx.browser.DjBrowserHost;
import org.NooLab.itexx.browser.DjBrowserHostIntf;
import org.NooLab.itexx.browser.DjBrowserListener;
import org.NooLab.itexx.retrieval.google.GooglePreProc;

import org.NooLab.utilities.files.DFutils;
import org.NooLab.utilities.logging.PrintLog;
import org.NooLab.utilities.objects.StringedObjects;

import chrriis.dj.nativeswing.swtimpl.components.JWebBrowser;

public class RetrievalDispatch {

	ITexxWindowIntf app;
	DjBrowserHost djBrowserHost; 
	DjBrowserListener listener;
	
	PrintLog out = new PrintLog(2,true);
	private BrowserWorker swingWorker;
	private JWebBrowser webBrowser;
	private ITexxWindowGuiIntf windowGui;
	private boolean completedDataProcessing;
	
	DFutils fileutil = new DFutils();
	// ========================================================================
	public RetrievalDispatch( ITexxWindowIntf app, 
							  DjBrowserHost djBrowserHost, 
							  DjBrowserListener listener) {
		// 
		this.app = app;
		this.djBrowserHost = djBrowserHost;
		this.listener = listener;
		
		windowGui = app.getWindowGui();
		webBrowser = djBrowserHost.getWebBrowser();
	}
	
	// ========================================================================
	
	
	public void handlingData(Object pageStrObj) throws IOException {

		PageIntf page=null;
		String url="" ;
		int s1,s2;
		
		if (completedDataProcessing ){
			return;
		}
		completedDataProcessing = true;
		
		listener.stopCompletionDetector();
		
		updateReferences();
		
		if (out!=null){
			out.print(2, "         LOADING  C O M P L E T E D ! ! ");
			out.delay(10);
		}else{
			System.out.println( "LOADING  C O M P L E T E D ! ! ");
		}
		StringedObjects so = new StringedObjects();
		
		Page pp;
		int p ;
		if (pageStrObj instanceof PageIntf){
			url = ((PageIntf)pageStrObj).getContextUrl() ;
			page = ((PageIntf)pageStrObj);
			
			p = page.getHTML().indexOf("class=r"); // quick test for google search result items
			if (p>0){
				out.setPrefix("[iTexx-Gui]");
				out.print(2, "page is ok...");
			}
			
			out.printErr(3, "\n"+">>>>>   secret of page : "+page.getSecret() );
			out.printErr(3, "\n"+">>>>>       request id : "+page.getRequestID() );
			if (url.toLowerCase().contains(".google.")){
				if ((page.getHTML().toLowerCase().contains("<div id=search")==false) && (page.getHTML().toLowerCase().contains("id=\"search\"")==false)){
					
					out.print(2,"last buffer file (3): "+ page.getKnownBufferFile());
					
					String tmpFile = fileutil.createpath( fileutil.getTempDir(), "~itx-denied-file.txt") ;
					fileutil.writeFileSimple( tmpFile, page.getHTML()) ;
					
					return; // defending against google's handshake mechanism to identify human users
				}
			}
			
		}
		if ((url.length()>0) && (app.getAppCommons().isEarlyPreprocessing(url))){
			// <div id="search">
			

			if (url.length()>0){
				String str = so.encode(page);
				page = (PageIntf) so.decode(str) ;
			}

			s1 = page.getHTML().length();
			
			// (new GooglePreProc()).reduceRawGoogleHtml(page);
			// (new GooglePreProc()).removeSearchField(page);

			/*
			
			String tmpFile = "DFutils.getTempFile("googlehtml-0.html");
			(new DFutils()).writeFileSimple( tmpFile, page.getHTML()) ;

			*/
			(new GooglePreProc()).selectSearchResults(page);
			
			
			// DEBUG ONLY
			// (swingWorker = new BrowserWorker( webBrowser,page )).execute();
			// DEB ONLY end
			
			s2 = page.getHTML().length();
			if ((s2!=s1) && (s2>50)){
				// we set the preprocessed html
				listener.setInternalClient("RetrievalDispatch");
				out.delay(100) ;
				(swingWorker = new BrowserWorker( webBrowser,page, listener )).execute(); 
			}
			
		}
		if ((page==null) || (url.length()==0)){
			return;
		}
		// get latest data about focus context from gui  
		app.getAppCommons().getModelController().updateFocusDataFromGui();
		
		// save this search to history using the session manager
		app.getAppCommons().getSessionManager().getHistory().addItem(url) ;
		
		
		// this calls the HtmlConsumer (which cares for storage according to settings)
		// and updates the Gui
		
		completedDataProcessing = false;
		if (url.length()>0){
			ResultsDigester rd;
			/*
			 * this creates an instance of SearchEngineResults, and by doing this it also
			 * lets it (SearchEngineResults) know about the ResultsDigester we create below
			 *  
			 */
			
			// The RetrievalEngine sets collecing on/off, which reflects whether there a several pages 
			// from the search engine 
			DjBrowserHostIntf wbHost = app.getAppCommons().getHostList().get(0);
			if (wbHost.isCollecting()){
				// we have to install a local heap, in both cases FIXME 
			}else{
				
			}
			
								out.print(2, "ResultsDigester is now going to start the inspection of the SearchEngineResults...") ;
			(rd = new ResultsDigester(app, djBrowserHost.isCollecting())).go(pageStrObj);
		}
		//System.out.println("\nreceived string : \n"+ (String)pageStrObj ) ;

		
	}
	
	
	private void updateReferences(){
		windowGui = app.getAppCommons().getWindowGui();
		out = windowGui.getOut();
		// htmlConsumer = app.getAppCommons().getHtmlConsumer();

	}
	

	
	

}
